package cn.ren.cloud.mq.consumer;

import cn.ren.cloud.domain.CourseOrder;
import cn.ren.cloud.dto.CourseOrderExtParamsDto;
import cn.ren.cloud.enums.GlobelExceptionEnum;
import cn.ren.cloud.exception.GlobalCustomException;
import cn.ren.cloud.service.ICourseOrderService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * @author 23508
 */
@Slf4j
@Component
@RocketMQMessageListener(
        consumerGroup = "order-handler-group",
        topic = "pay-order-topic",
        selectorExpression = "pay-order-tag",
        messageModel = MessageModel.BROADCASTING
)
public class OrderHandlerConsumer implements RocketMQListener<MessageExt> {

    private final ICourseOrderService courseOrderService;

    public OrderHandlerConsumer(ICourseOrderService courseOrderService) {
        this.courseOrderService = courseOrderService;
    }

    @Override
    public void onMessage(MessageExt messageExt) {
        // 1.参数校验
        byte[] body = messageExt.getBody();
        if (body.length == 0) {
            // 1.记录进入异常的次数，如果超过三次，手动处理
            log.error("支付后订单结果处理发生异常，异常信息为：消息信息为空！");
            throw new GlobalCustomException(GlobelExceptionEnum.GLOBE_EXCEPTION_ENUM_PARAM_ERROR);
        }

        CourseOrderExtParamsDto courseOrderExtParamsDto = JSON.parseObject(new String(body, StandardCharsets.UTF_8), CourseOrderExtParamsDto.class);

        // 2.业务校验
        String orderNo = courseOrderExtParamsDto.getOrderNo();
        // 查询订单号
        CourseOrder courseOrder = courseOrderService.selectByOrderNo(orderNo);

        if (courseOrder == null) {
            log.error("订单不存在，订单号为：" + orderNo);
            return;
        }
        // 获取订单状态
        Integer statusOrder = courseOrder.getStatusOrder();
        if (!CourseOrder.WAIT_PAY.equals(statusOrder)) {
            log.error("订单状态异常，订单号为：{}，订单状态为：{}", orderNo, statusOrder);
            return;
        }
        // 修改订单状态和修改时间
        courseOrder.setStatusOrder(CourseOrder.SUCCESS_PAY);
        courseOrder.setUpdateTime(new Date());
        courseOrderService.updateById(courseOrder);
    }
}
